import { SingleMessageItem } from '@/entity/SingleMessageItem.class.js';
export class MessageManager {
	originalDataList = [];
	messageDataList = [];
	maxDiffTimestamp = 3 * 60;
	reverse = true
	handle = null

	constructor(reverse = true) {
		console.log(reverse)
		this.reverse = reverse;
	}

	// 记录聊天记录
	log(data = null) {
		//判断非法调用或不合法的参数
		if (!data && typeof data != 'object') {
			return false
		}
		//深度克隆原始数据，避免监听或内存地址的影响
		let originalDataList = this.deepClone(this.originalDataList)
		//判断插入的是数组还是对象，允许插入多条消息记录
		if (this.isArray(data)) {
			originalDataList.push(...data)
		} else {
			originalDataList.push(data)
		}
		originalDataList = this.handleTimestamp(this.sortMessage(originalDataList))
		this.messageDataList = this.conversionMessage(originalDataList);
		this.originalDataList = originalDataList;
		return true
	}
	// 发送聊天记录
	send(data = null, to, type = "single") {
		if (!data && !to && typeof data != 'object') {
			return false
		}
		const length = this.originalDataList.push(data);
		this.originalDataList = this.handleTimestamp()
		this.messageDataList.push((new SingleMessageItem({ ...this.originalDataList[length - 1], sendSuccess: this.handle }, 0)))
		this.messageDataList[length - 1].sendMessage(to, type)
		return true;
	}

	addHandle(handle = null) {
		this.handle = handle
	}

	//撤回消息处理
	revokeMessage(data = {}) {


	}

	//手动对时间戳进行排序，避免因为异步导致的消息乱序问题
	sortMessage(list) {
		return list.sort((a, b) => {
			if (this.reverse) {
				return a.timestamp - b.timestamp;
			} else {
				return b.timestamp - a.timestamp;
			}
		})
	}

	conversionMessage(list) {
		const data = []
		for (let item of list) {
			data.push(new SingleMessageItem(item))
		}
		return data

	}


	//对消息时间做差值，减少时间的出现
	handleTimestamp(list = this.originalDataList) {
		const length = list.length;
		for (let i = 0; i < list.length; i++) {
			if (!!list[length - i - 1] && !!list[length - i - 2]) {
				if (Math.abs(list[length - i - 1].timestamp - list[length - i - 2].timestamp) <= this.maxDiffTimestamp) {
					list[length - i - 1].hideTimestamp = true;
				}
			}

		}
		return list;
	}

	clear() {
		this.originalDataList = [];
		this.messageDataList = [];
	}




	//直接抄深度克隆就不用引用
	isArray(arr) {
		return Object.prototype.toString.call(arr) === '[object Array]';
	}

	deepClone(obj) {
		// 对常见的“非”值，直接返回原来值
		if ([null, undefined, NaN, false].includes(obj)) return obj;
		if (typeof obj !== "object" && typeof obj !== 'function') {
			//原始类型直接返回
			return obj;
		}
		var o = this.isArray(obj) ? [] : {};
		for (let i in obj) {
			if (obj.hasOwnProperty(i)) {
				o[i] = typeof obj[i] === "object" ? this.deepClone(obj[i]) : obj[i];
			}
		}
		return o;
	}

}
